package center

import (
	"base"
	"gate_server/chanrpc"
	. "gate_server/internal"
	"gate_server/logic/center/api"
	. "gate_server/logic/internal"
	"github.com/golang/protobuf/proto"
	"leaf/gate"
	"proto/base"
	"proto/server/center"
)

type centerSystem struct {
	agent gate.Agent
}

var (
	system = new(centerSystem)
)

func init() {
	center_api.WriteMsg = system.WriteMsg
}

func init() {
	Skeleton.AfterInit(func() {
		Skeleton.RegisterChanRPC(chanrpc.NewCenterAgent, system.newAgent)
		Skeleton.RegisterChanRPC(chanrpc.CloseCenterAgent, system.closeAgent)
	})
}

func (*centerSystem) newAgent(args []interface{}) {
	agent := args[0].(gate.Agent)
	base.Logger.Debug("new center server agent, remote address: %s, local address: %s", agent.RemoteAddr(), agent.LocalAddr())

	system.agent = agent
	system.register()
}

func (*centerSystem) register() {
	msg := new(proto_server_center.Register)
	msg.Server = proto_base.Server_GateServer
	msg.Data = []byte(Config.InternalAddr)

	system.WriteMsg(msg)
}

func (*centerSystem) closeAgent(args []interface{}) {
	agent := args[0].(gate.Agent)
	base.Logger.Debug("close center server agent, remote address: %s, local address: %s", agent.RemoteAddr(), agent.LocalAddr())

	system.agent = nil
}

func (*centerSystem) WriteMsg(msg proto.Message) {
	if system.agent == nil {
		base.Logger.Warning("not connect center center")
		return
	}

	system.agent.WriteMsg(msg)
}
